package cn.tedu.csmall.product.ex.handler;

import cn.tedu.csmall.product.ex.ServiceException;
import cn.tedu.csmall.product.web.JsonResult;
import cn.tedu.csmall.product.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;

/**
 * 全局异常处理器
 *
 * @author liuweitao
 * @version 1.0.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    public GlobalExceptionHandler() {
        System.out.println("创建全局异常处理器");
    }

    //处理Service异常，返回给页面的内容
    @ExceptionHandler
    public JsonResult handlerServiceException(ServiceException e){
        log.debug("捕获到ServiceException异常：{}",e.getMessage());

        return JsonResult.fail(e);
    }

    //处理Spring Validation检查出来的封装类请求参数有误的异常
    @ExceptionHandler
    public JsonResult handlerBindException(BindException e){
        log.debug("捕获到BindException异常：{}",e.getMessage());

//        以下2行代码，如果有多种错误时，将随机获取其中1种错误的信息，并响应

        String message = e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);

        // 以下代码，如果有多种错误时，将获取所有错误信息，并响应
/*
        String delimiter = ",";
        String prefix = "添加相册失败";
        String suffix = "！";
        StringJoiner stringJoiner = new StringJoiner(delimiter,prefix,suffix);
        //        StringBuilder stringBuilder = new StringBuilder();
        List<FieldError> fieldErrors = e.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            String defaultMessage = fieldError.getDefaultMessage();
            stringJoiner.add(defaultMessage);
        }
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,stringJoiner.toString());
        */

    }

    @ExceptionHandler
    public JsonResult handlerConstraintViolationException(ConstraintViolationException e){
        log.debug("捕获到ConstraintViolationException异常：{}",e.getMessage());

        String delimiter = ",";//前缀
        String prefix = "添加相册失败,";//内容
        String suffix = "！";//后缀
        StringJoiner stringJoiner = new StringJoiner(delimiter,prefix,suffix);//三个参数：前缀 内容 后缀
//        StringBuilder builder = new StringBuilder();
        /*解决e.getMessage()错误信息包含方法名和参数名，
        使用constraintViolation.getMessage()可以去掉方法名和参数名，仅输出报错的信息*/
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            String defaultMessage = constraintViolation.getMessage();
            stringJoiner.add(defaultMessage);
        }
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,stringJoiner.toString());
    }

    @ExceptionHandler
    public String handlerNullPointerException(NullPointerException e){
        log.debug("捕获到NullPointerException异常：{}",e.getMessage());
        return e.getMessage();
    }

    @ExceptionHandler
    public String handlerRuntimeException(RuntimeException e){
        log.debug("捕获到RuntimeException异常：{}",e.getMessage());
        e.printStackTrace();
        return e.getMessage();
    }

    /*AccessDeniedException*/
    @ExceptionHandler
    public JsonResult<Void> handlerAccessDeniedException(AccessDeniedException e){
        log.error("捕获到AccessDeniedException异常：{}",e.getMessage());
        String message = "请求失败，该管理员账号权限不足";
        return JsonResult.fail(ServiceCode.ERR_FORBIDDEN,message);
    }

    @ExceptionHandler
    public String handlerHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
        log.debug("捕获到HttpRequestMethodNotSupportedException：{}",e.getMethod());
        return "非法访问";
    }

    @ExceptionHandler
    public String handlerThrowable(Throwable e){
        log.debug("捕获到Throwable异常：{}",e.getMessage());
        e.printStackTrace();//强烈建议，仅在开发过程中建议，因为会导致系统资源被占用
        return "未知错误，请联系管理员";
    }
}
